import React, { useCallback, useEffect } from 'react';
import moment from 'moment';
import { Form, DatePicker, Table, Icon, Button } from 'antd';
import { formatMessage } from 'umi';
import classNames from 'classnames';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Pagination from '@/components/Pagination';
import OrganizationSelect from '@/components/OrganizationSelect';
import { SearchInput } from '@/components/UserForm';
import { isSuccess } from '@/utils/request';
import AuthComponent from '@/utils/auth/AuthComponent';

import BaseSettingProvider from '@/pages/SalaryManage/components/BaseSettingProvider';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import { queryEmployeeList } from '@/services/salaryManage/salaryCommon';
import ExcelUploader from '@/pages/SalaryManage/SalaryCalculate/ImportExcel/ExcelUploader';
import SalaryConfigTipPage from '@/pages/SalaryManage/components/SalaryConfigTipPage';
import useHistoryBlock from '@/pages/SalaryManage/hooks/useHistoryBlock';
import { useHandleRefreshMessage } from '@/pages/SalaryManage/utils/tabMessageUtil';

import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import styles from '@/pages/SalaryManage/SalaryCalculate/ImportExcel/index.less';
import ImportExcelRouter from './component/ImportExcelRouter';
import ImportExcelMenuFilter from './component/ImportExcelMenuFilter';

const { MonthPicker } = DatePicker;
const namespace = 'importExcelModel';

const ExcelList = ({
    searchModel,
    columns,
    dataSource,
    rowKey,
    pagination,
    loading,
    showImportDialog,
    uploadAction,
    showTemplateButton,
    user,
    dispatchType,
    dispatch,
    uploadExtra,
    uploadExtraParams,
    form,
    goToLog,
    goToEdit,
    history,
    importAuthCode,
    selectOrganizationCode,
    organizationResponse
}) => {
    const {
        initType,
        changePeriodType,
        tablePageChangeType,
        searchType,
        showImportDialogType,
        setMultiStoreType,
        deleteType
    } = dispatchType;

    useEffect(
        () => () => {
            dispatch({
                type: showImportDialogType,
                payload: false
            });
        },
        []
    );

    // 1.设置默认选择月份
    const periodMoment = searchModel.period ? moment(searchModel.period) : null;

    function onChange(date, dateString) {
        dispatch({
            type: changePeriodType,
            payload: dateString
        });
        dispatch({
            type: searchType
        });
    }

    function onEmployeeChange(employeeCode) {
        dispatch({
            type: setMultiStoreType,
            payload: { searchModel: { ...searchModel, employeeCode } }
        });
        dispatch({
            type: searchType
        });
    }

    const tablePageChange = ({ current, pageSize }) => {
        dispatch({
            type: tablePageChangeType,
            payload: { current, pageSize }
        });
    };

    const importExcel = () => {
        dispatch({
            type: showImportDialogType,
            payload: true
        });
    };

    const { getFieldDecorator } = form;

    const operateAction = {
        onEdit(record) {
            goToEdit(record);
        },
        onDelete(record) {
            dispatch({
                type: deleteType,
                payload: record.id,
                currentRecord: record
            });
        }
    };

    useEffect(() => {
        if (selectOrganizationCode) {
            dispatch({ type: initType, payload: { organizationCode: selectOrganizationCode, needReset: true } });
        }
    }, [selectOrganizationCode]);

    useHistoryBlock(history, (/* location, unBlock */) => {
        dispatch({
            type: showImportDialogType,
            payload: false
        });
    });

    const handleOrganizationChange = useCallback(
        value => {
            if (selectOrganizationCode !== value) {
                dispatch({
                    type: `${namespace}/setMultiStore`,
                    payload: {
                        selectOrganizationCode: value,
                        countryNameCode: null
                    }
                });
            }
        },
        [selectOrganizationCode]
    );

    useHandleRefreshMessage();

    return (
        <PageHeaderWrapper type="success">
            <BaseSettingProvider organizationCode={selectOrganizationCode}>
                <ImportExcelMenuFilter>
                    <ImportExcelRouter
                        type="salaryExcelImport"
                        extraButton={
                            <div className={salaryStyle.flex}>
                                <div className={classNames([salaryStyle.flex, salaryStyle.mr12])}>
                                    <OrganizationSelect
                                        isStrictly
                                        isNeedPermission
                                        style={{ width: 220 }}
                                        onChange={handleOrganizationChange}
                                        value={selectOrganizationCode}
                                        allowClear={false}
                                        dropdownMatchSelectWidth
                                        treeDataFromProp
                                        treeDataList={organizationResponse}
                                    />
                                </div>
                                <div>
                                    <Button onClick={() => goToLog(selectOrganizationCode)}>操作日志</Button>
                                </div>
                            </div>
                        }
                    >
                        <SalaryConfigTipPage organizationCode={selectOrganizationCode}>
                            <div className={styles.salaryExcelBox}>
                                <TwoColHead
                                    left={
                                        <Form layout="inline">
                                            {/* 月份 */ formatMessage({ id: 'importExcel.month' })}：
                                            <MonthPicker
                                                onChange={onChange}
                                                suffixIcon={<Icon type="down" />}
                                                value={periodMoment}
                                                placeholder="请选择月份"
                                                style={{
                                                    verticalAlign: 'middle'
                                                }}
                                            />
                                            <span
                                                className={salaryStyle.ml16}
                                                style={{
                                                    display: 'inline-block',
                                                    overflow: 'auto',
                                                    width: '300px',
                                                    verticalAlign: 'middle'
                                                }}
                                            >
                                                <Form.Item
                                                    label="员工"
                                                    className={salaryStyle.flex}
                                                    style={{ width: '280px' }}
                                                >
                                                    {getFieldDecorator('employeeCode', {
                                                        ...(searchModel?.employeeCode
                                                            ? { initialValue: searchModel?.employeeCode }
                                                            : {})
                                                    })(
                                                        <SearchInput
                                                            params={{
                                                                organizationCode: selectOrganizationCode
                                                            }}
                                                            getData={async params => {
                                                                if (!params.organizationCode) {
                                                                    return [];
                                                                }
                                                                const employeeResponse = await queryEmployeeList({
                                                                    organizationCode: params.organizationCode
                                                                });
                                                                return isSuccess(employeeResponse)
                                                                    ? employeeResponse.data || []
                                                                    : [];
                                                            }}
                                                            selectProps={{
                                                                placeholder: '请输入员工姓名',
                                                                allowClear: true,
                                                                getPopupContainer: () =>
                                                                    document.getElementsByClassName(
                                                                        styles.salaryExcelBox
                                                                    )[0]
                                                            }}
                                                            fieldsName={{
                                                                value: 'employeeCode',
                                                                title: 'name'
                                                            }}
                                                            onChange={onEmployeeChange}
                                                        />
                                                    )}
                                                </Form.Item>
                                            </span>
                                        </Form>
                                    }
                                    right={
                                        <AuthComponent code={importAuthCode}>
                                            <Button type="primary" onClick={importExcel}>
                                                {/* 导入 */ formatMessage({ id: 'importExcel.import' })}
                                            </Button>
                                        </AuthComponent>
                                    }
                                />

                                <div className={styles.tableBox}>
                                    <Table
                                        bordered
                                        columns={
                                            typeof columns === 'function' ? columns(pagination, operateAction) : columns
                                        }
                                        rowKey={rowKey}
                                        dataSource={dataSource}
                                        pagination={false}
                                        loading={loading.effects[searchType]}
                                        scroll={{ x: 1510 }}
                                    />
                                </div>
                                <Pagination {...pagination} onChange={tablePageChange} />
                            </div>

                            <ExcelUploader
                                showImportDialog={showImportDialog}
                                uploadAction={uploadAction}
                                dispatchType={dispatchType}
                                dispatch={dispatch}
                                showTemplateButton={showTemplateButton}
                                user={user}
                                extra={uploadExtra}
                                extraParams={uploadExtraParams}
                            />
                        </SalaryConfigTipPage>
                    </ImportExcelRouter>
                </ImportExcelMenuFilter>
            </BaseSettingProvider>
        </PageHeaderWrapper>
    );
};

export default Form.create()(ExcelList);
